# coding: utf-8
from PySide6.QtCore import QUrl, QSize
from PySide6.QtGui import QIcon, QColor
from PySide6.QtWidgets import QApplication, QWidget, QSystemTrayIcon
from PySide6.QtGui import QClipboard

from qfluentwidgets import NavigationItemPosition, FluentWindow, SplashScreen
from qfluentwidgets import FluentIcon as FIF
from qfluentwidgets import InfoBar, InfoBarPosition, SystemTrayMenu, Action

from .setting_interface import SettingInterface
from .ai_card_interface import AICardInterface
from .home_interface import HomeInterface
# from .user_center_interface import UserCenterInterface # 移除用户中心界面导入
from ..common.config import cfg
from ..common.icon import Icon
from ..common.signal_bus import signalBus
from ..common import resource


class MainWindow(FluentWindow):

    def __init__(self):
        super().__init__()
       
        self.initWindow()

        # 创建子界面
        self.homeInterface = HomeInterface(self)
        self.aiCardInterface = AICardInterface(self)
        # self.userCenterInterface = UserCenterInterface(self) # 移除用户中心界面实例
        self.settingInterface = SettingInterface(self)
        
        # 设置界面的objectName
        self.aiCardInterface.setObjectName("aiCard")
        # self.userCenterInterface.setObjectName("userCenter") # 移除用户中心界面的objectName设置

        # 将界面添加到堆栈窗口
        self.stackedWidget.addWidget(self.homeInterface)
        self.stackedWidget.addWidget(self.aiCardInterface)
        # self.stackedWidget.addWidget(self.userCenterInterface) # 移除用户中心界面到堆栈窗口
        self.stackedWidget.addWidget(self.settingInterface)

        # 设置用户ID (此处的userId是之前复制ID功能用的，可以保留或根据需求调整)
        self.userId = cfg.get(cfg.email) or "unknown_user" 

        self.connectSignalToSlot()

        # add items to navigation interface
        self.initNavigation()
        
        # 默认显示主页
        self.switchTo(self.homeInterface)

        self.initSystemTray()

    def connectSignalToSlot(self):
        signalBus.micaEnableChanged.connect(self.setMicaEffectEnabled)
        signalBus.switchToSampleCard.connect(self.switchToSample)

    def switchToSample(self, routeKey, index):
        """根据路由键切换到相应的界面"""
        interfaces = self.findChildren(QWidget)
        for w in interfaces:
            if w.objectName() == routeKey:
                self.stackedWidget.setCurrentWidget(w, False)

    def copyUserId(self):
        """复制用户ID(邮箱)到剪贴板"""
        clipboard = QApplication.clipboard()
        user_email_to_copy = cfg.get(cfg.email) or self.tr("邮箱未设置")
        clipboard.setText(user_email_to_copy)
        
        InfoBar.success(
            self.tr("复制成功"),
            self.tr('用户邮箱已复制到剪贴板'),
            position=InfoBarPosition.TOP,
            parent=self
        )

    def initNavigation(self):
        # self.navigationInterface.setAcrylicEnabled(True)

        self.addSubInterface(self.homeInterface, FIF.HOME, self.tr('主页'))
        
        self.navigationInterface.addItem(
            routeKey="aiLearning",
            icon=FIF.IOT,
            text="AI学习",
            onClick=None,
            selectable=False,
            position=NavigationItemPosition.SCROLL,
        )
        
        self.navigationInterface.addItem(
            routeKey="aiCard",
            icon=FIF.QUICK_NOTE,
            text="AI制卡",
            onClick=lambda: self.switchTo(self.aiCardInterface),
            selectable=True,
            position=NavigationItemPosition.SCROLL,
            parentRouteKey="aiLearning",
        )

        # 移除之前的用户中心菜单项
        # self.addSubInterface(self.userCenterInterface, FIF.PEOPLE, self.tr('用户中心'), NavigationItemPosition.BOTTOM)

        # 添加显示邮箱的菜单项 (在底部)
        user_email = cfg.get(cfg.email)
        email_display_text = f"{user_email}" if user_email else self.tr("邮箱: 未登录/未设置")
        self.navigationInterface.addItem(
            routeKey="displayEmail",
            icon=FIF.MAIL, # 可以选择一个合适的图标
            text=email_display_text,
            onClick=self.copyUserId, # 点击复制邮箱
            selectable=False, # 不可选中切换视图，仅作显示和触发动作
            position=NavigationItemPosition.BOTTOM,
        )

        # 添加退出登录菜单项 (在底部，邮箱下方)
        self.navigationInterface.addItem(
            routeKey="userLogout",
            icon=FIF.LEFT_ARROW, # 使用退出图标
            text=self.tr('退出登录'),
            onClick=self.logout, # 点击时调用logout方法
            selectable=False, # 通常退出按钮不保持选中状态
            position=NavigationItemPosition.BOTTOM,
        )

        self.addSubInterface(
            self.settingInterface, FIF.SETTING, self.tr('Settings'), NavigationItemPosition.BOTTOM)

        self.splashScreen.finish()

    def logout(self):
        """退出登录，返回到登录界面"""
        cfg.set(cfg.autoLogin, False)
        cfg.set(cfg.jwtToken, "")
        # Hide the tray icon before closing to prevent multiple tray icons
        self.trayIcon.hide()
        from .register_window import AuthWindow
        self.close()
        self.loginWindow = AuthWindow()
        self.loginWindow.show()
        
    # def openUserCenter(self): # 此方法不再需要，可以移除
    #     self.switchTo(self.userCenterInterface)

    def initWindow(self):
        self.resize(960, 780)
        self.setMinimumWidth(760)
        self.setWindowIcon(QIcon(':/app/images/logo.png'))
        self.setWindowTitle('智拓AI')

        self.setCustomBackgroundColor(QColor(240, 244, 249), QColor(32, 32, 32))
        self.setMicaEffectEnabled(cfg.get(cfg.micaEnabled))

        self.splashScreen = SplashScreen(self.windowIcon(), self)
        self.splashScreen.setIconSize(QSize(106, 106))
        self.splashScreen.raise_()

        desktop = QApplication.primaryScreen().availableGeometry()
        w, h = desktop.width(), desktop.height()
        self.move(w//2 - self.width()//2, h//2 - self.height()//2)
        self.show()
        QApplication.processEvents()

    def resizeEvent(self, e):
        super().resizeEvent(e)
        if hasattr(self, 'splashScreen'):
            self.splashScreen.resize(self.size())

    def initSystemTray(self):
        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.setIcon(QIcon(':/app/images/logo.png'))
        self.trayIcon.setToolTip(self.tr("智拓AI"))

        self.trayMenu = SystemTrayMenu(parent=self)
        self.showAction = Action(FIF.HOME, self.tr("显示"), self)
        self.quitAction = Action(FIF.CLOSE, self.tr("退出"), self)

        self.trayMenu.addAction(self.showAction)
        self.trayMenu.addAction(self.quitAction)

        self.trayIcon.setContextMenu(self.trayMenu)

        self.showAction.triggered.connect(self.show)
        self.quitAction.triggered.connect(self.forceQuit)
        self.trayIcon.activated.connect(self.onTrayIconActivated)

        self.trayIcon.show()

    def onTrayIconActivated(self, reason):
        if reason == QSystemTrayIcon.ActivationReason.DoubleClick:
            self.showNormal()
            self.activateWindow()

    def closeEvent(self, event):
        if self.trayIcon.isVisible():
            self.hide()
            event.ignore()
        else:
            super().closeEvent(event)

    def forceQuit(self):
        self.trayIcon.hide()
        QApplication.quit()